import { Toast } from 'ng-zorro-antd-mobile';
import { Injectable } from '@angular/core'
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http'
import { Observable } from 'rxjs'
import { finalize, tap } from 'rxjs/operators';
import { CoolLocalStorage } from '../coolStorage/cool-local-storage'

@Injectable()
export class NoopInterceptor implements HttpInterceptor {

    constructor(
        private localStorage: CoolLocalStorage,
        private _toast: Toast,
    ) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let token = this.localStorage.getItem('token') || ''
        let location = this.localStorage.getObject('location')
        let header = {}
        let authReq = req
        if (token) {
            header['Token'] = token
        }
        if (location) {
            header['latitude'] = location['latitude']
            header['longitude'] = location['longitude']
        }
        if (header) {
            authReq = req.clone({ setHeaders: header })
        }

        // setTimeout(() => {
        //     Toast.loading('加载中...', 0)
        // }, 1);

        return next.handle(authReq).pipe(
            tap(
                // Succeeds when there is a response; ignore other events
                event => {
                    // console.log(event instanceof HttpResponse ? 'succeeded' : '');
                },
                // Operation failed; error is an HttpErrorResponse
                error => {
                    // console.log(error);
                }
            ),
            // Log when response observable either completes or errors
            finalize(() => {

                // setTimeout(() => {
                    // Toast.hide();
                // }, 800);
            })
        );
    }
}
